<template>
  <div class="country-select-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <van-icon name="arrow-left" @click="goBack" class="back-icon" />
      <div class="title">选择国家和地区</div>
      <div class="placeholder"></div>
    </div>

    <!-- 搜索框 -->
    <div class="search-container">
      <van-field
        v-model="searchKeyword"
        placeholder="搜索"
        @update:model-value="handleInputChange"
        @clear="handleClear"
        clearable
      >
        <template #left-icon>
          <van-icon name="search" />
        </template>
      </van-field>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 滚动容器 -->
      <div class="scroll-container">
        <template v-if="searchKeyword">
          <!-- 搜索结果 -->
          <div class="country-list">
            <div
              v-for="country in filteredCountries"
              :key="country.countryCode"
              class="country-item"
              :class="{ selected: selectedCountryCode === country.countryCode }"
              @click="selectCountry(country)"
            >
              <!-- <span class="country-flag">{{ country.flag }}</span> -->
              <span class="country-name">{{ country.name }}</span>
              <span class="country-code">{{ country.code }}</span>
              <van-icon
                v-if="selectedCountryCode === country.countryCode"
                name="success"
                class="selected-icon"
              />
            </div>
          </div>
        </template>

        <template v-else>
          <!-- 热门国家 -->
          <div class="hot-countries">
            <div class="section-title">热门国家和地区</div>
            <div class="hot-country-list">
              <div
                v-for="country in hotCountries"
                :key="country.countryCode"
                class="hot-country-item"
                :class="{
                  selected: selectedCountryCode === country.countryCode,
                }"
                @click="selectCountry(country)"
              >
                <span class="country-name">{{ country.name }}</span>
                <span class="country-code">{{ country.code }}</span>
                <van-icon
                  v-if="selectedCountryCode === country.countryCode"
                  name="success"
                  class="selected-icon"
                />
              </div>
            </div>
          </div>

          <!-- 按字母分组的国家列表 -->
          <div
            v-for="(group, letter) in groupedCountries"
            :key="letter"
            class="letter-group"
            :id="`letter-${letter}`"
          >
            <div class="letter-title">{{ letter }}</div>
            <div class="country-list">
              <div
                v-for="country in group"
                :key="country.countryCode"
                class="country-item"
                :class="{
                  selected: selectedCountryCode === country.countryCode,
                }"
                @click="selectCountry(country)"
              >
                <!-- <span class="country-flag">{{ country.flag }}</span> -->
                <span class="country-name">{{ country.name }}</span>
                <span class="country-code">{{ country.code }}</span>
                <van-icon
                  v-if="selectedCountryCode === country.countryCode"
                  name="success"
                  class="selected-icon"
                />
              </div>
            </div>
          </div>
        </template>
      </div>

      <!-- 右侧字母索引 -->
      <div class="alphabet-sidebar" v-if="!searchKeyword">
        <div
          v-for="letter in alphabetLetters"
          :key="letter"
          class="alphabet-item"
          @click="scrollToLetter(letter)"
        >
          {{ letter }}
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from "vue";
import { useRouter } from "vue-router";
import countriesData from "@/data/countries.json";
import { chineseToLetter ,countryPinyinMap,alphabetLetters} from "@/data/chineseToLetter";

// 定义国家类型
interface Country {
  name: string;
  code: string;
  countryCode: string;
  flag: string;
}

const router = useRouter();

// 数据
const countries = ref<Country[]>(countriesData);
const searchKeyword = ref("");
const filteredCountries = ref<Country[]>([]);
const scrollTimer = ref<NodeJS.Timeout | null>(null);
const selectedCountryCode = ref<string>("");

// 热门国家（前10个）
const hotCountries = computed(() => countries.value.slice(0, 10));


// 按字母分组的国家
const groupedCountries = computed(() => {
  const groups: Record<string, Country[]> = {};

  countries.value.forEach((country) => {
    let letter: string;

    // 检查是否是中文国家名称
    if (chineseToLetter[country.name]) {
      letter = chineseToLetter[country.name];
    } else {
      // 获取国家名称的首字母，直接转换为大写字母
      const firstChar = country.name.charAt(0).toUpperCase();
      // 如果不是A-Z字母，则根据字符编码映射到最接近的字母
      if (/[A-Z]/.test(firstChar)) {
        letter = firstChar;
      } else {
        // 对于非英文字符，根据Unicode编码映射到字母
        const charCode = firstChar.charCodeAt(0);
        if (charCode >= 192 && charCode <= 197) letter = "A"; // À-Å
        else if (charCode >= 199 && charCode <= 199) letter = "C"; // Ç
        else if (charCode >= 200 && charCode <= 203) letter = "E"; // È-Ë
        else if (charCode >= 204 && charCode <= 207) letter = "I"; // Ì-Ï
        else if (charCode >= 209 && charCode <= 209) letter = "N"; // Ñ
        else if (charCode >= 210 && charCode <= 216) letter = "O"; // Ò-Ö
        else if (charCode >= 217 && charCode <= 220) letter = "U"; // Ù-Ü
        else if (charCode >= 221 && charCode <= 221) letter = "Y"; // Ý
        else {
          // 其他字符按首字母处理，如果是数字或特殊字符，映射到最接近的字母
          const normalizedChar = firstChar
            .normalize("NFD")
            .replace(/[\u0300-\u036f]/g, "");
          letter = /[A-Z]/.test(normalizedChar) ? normalizedChar : "A";
        }
      }
    }

    if (!groups[letter]) {
      groups[letter] = [];
    }
    groups[letter].push(country);
  });

  // 按字母排序，只包含A-Z字母
  const sortedGroups: Record<string, Country[]> = {};
  alphabetLetters.forEach((letter) => {
    if (groups[letter]) {
      sortedGroups[letter] = groups[letter].sort((a, b) =>
        a.name.localeCompare(b.name)
      );
    }
  });

  return sortedGroups;
});

// 方法
const goBack = () => {
  router.back();
};

const selectCountry = (country: Country) => {
  // 更新选中的国家代码
  selectedCountryCode.value = country.countryCode;

  // 存储到sessionStorage中
  sessionStorage.setItem("selectedCountryCode", country.countryCode);

  // 获取来源页面
  const from = router.currentRoute.value.query.from as string;

  if (from === "register") {
    // 返回注册页面并传递选择的国家
    router.push({
      path: "/register",
      query: {
        selectedCountry: country.countryCode,
      },
    });
  } else {
    // 默认返回上一页
    router.back();
  }
};



const filterCountries = (value?: string | any) => {
  // 使用传入的值或当前的searchKeyword值，确保转换为字符串
  const currentValue =
    value !== undefined ? String(value) : String(searchKeyword.value || "");
  console.log(currentValue, "---searchKeyword");

  // 检查是否为空字符串或只包含空格
  if (!currentValue || currentValue.trim() === "") {
    filteredCountries.value = [];
    return;
  }

  const keyword = currentValue.toLowerCase().trim();
  console.log(keyword, "-keyword");

  filteredCountries.value = countries.value.filter((country: Country) => {
    // 基础匹配：国家名称、代码、国家代码
    const basicMatch =
      country.name.toLowerCase().includes(keyword) ||
      country.code.toLowerCase().includes(keyword) ||
      country.countryCode.toLowerCase().includes(keyword);

    // 中文模糊匹配：优化匹配逻辑
    let chineseMatch = false;
    if (keyword.length === 1) {
      // 单字符匹配：在国家名称中查找
      chineseMatch = country.name.includes(keyword);
    } else {
      // 多字符匹配：从开头开始或包含连续字符
      chineseMatch =
        country.name.startsWith(keyword) || country.name.includes(keyword);
    }

    // 拼音匹配：支持拼音开头匹配
    let pinyinMatch = false;
    if (countryPinyinMap[country.name]) {
      pinyinMatch = countryPinyinMap[country.name].some((pinyin) => {
        return (
          pinyin.startsWith(keyword) ||
          (keyword.length === 1 && pinyin.includes(keyword))
        );
      });
    }

    return basicMatch || chineseMatch || pinyinMatch;
  });

  console.log("搜索结果:", filteredCountries.value.length);
};

// 处理输入变化
const handleInputChange = (value: any) => {
  // 确保值为字符串类型
  const inputValue = String(value || "");
  console.log("输入变化:", inputValue, "类型:", typeof value);

  // 直接使用传入的值，不需要手动设置searchKeyword
  // 因为v-model会自动同步
  filterCountries(inputValue);
};

// 处理清空按钮
const handleClear = () => {
  console.log("清空按钮点击");
  searchKeyword.value = "";
  filteredCountries.value = [];
  console.log("搜索框已清空");
};

// 监听搜索关键词变化（作为备用机制）
watch(
  searchKeyword,
  (newValue, oldValue) => {
    console.log("watch触发:", newValue, "旧值:", oldValue);
    // 只在输入事件没有正确触发时作为备用
    if (newValue !== oldValue) {
      console.log("watch备用触发搜索");
      filterCountries(newValue);
    }
  },
  { immediate: false, flush: "post" }
);

const scrollToLetter = (letter: string) => {
  const element = document.getElementById(`letter-${letter}`);
  if (element) {
    element.scrollIntoView({ behavior: "smooth" });
  }
};

// 滚动监听函数
const handleScroll = () => {
  // 清除之前的定时器
  if (scrollTimer.value) {
    clearTimeout(scrollTimer.value);
  }
};

// 初始化
onMounted(() => {
  // 初始化时不设置filteredCountries，保持为空数组
  filteredCountries.value = [];

  // 获取当前选中的国家代码
  const currentRoute = router.currentRoute.value;
  if (currentRoute.query.from === "register") {
    // 从注册页面来的，需要获取当前选中的国家
    const registerRoute = router
      .getRoutes()
      .find((route) => route.path === "/register");
    // 通过sessionStorage或其他方式获取当前选中的国家
    const storedCountryCode = sessionStorage.getItem("selectedCountryCode");
    if (storedCountryCode) {
      selectedCountryCode.value = storedCountryCode;
    }
  }

  // 添加滚动监听
  nextTick(() => {
    const scrollContainer = document.querySelector(".scroll-container");
    if (scrollContainer) {
      scrollContainer.addEventListener("scroll", handleScroll);
    }
  });
});

// 清理
onUnmounted(() => {
  if (scrollTimer.value) {
    clearTimeout(scrollTimer.value);
  }

  const scrollContainer = document.querySelector(".scroll-container");
  if (scrollContainer) {
    scrollContainer.removeEventListener("scroll", handleScroll);
  }
});
</script>

<style lang="scss" scoped>
@import url('./style/index.scss');
</style>